/*
 * Copyright (C) 2012 yueyueniao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wzm.moviepic.fragment;

import java.util.ArrayList;

import com.wzm.bean.DownInfo;
import com.wzm.bean.HistoryBean;
import com.wzm.bean.MovieInfo;
import com.wzm.db.DBHelper;
import com.wzm.manager.ManagerTab;
import com.wzm.moviepic.R;
import com.wzm.moviepic.slidingmenu.Main1Activity;
import com.wzm.utils.FileUtils;
import com.wzm.utils.Logger;
import com.wzm.utils.MemoryStatus;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 本地下载数据
 * @author zhengzhiyou
 */
@SuppressLint("ValidFragment")
public class LocalFileFragment extends Fragment {

	private ListView fileList = null;
	private LFileAdapter fAdapter = null;
	private Context mContext;
	private ArrayList<DownInfo> fList = new ArrayList<DownInfo>();
	
	private TextView tv_allsize = null;
	private long allfilesize = 0;
	
	private ImageView btn_back;
	
	private ImageView btn_local_delall;
	private TextView tv_sydl;
	
	//手势
	//private GestureDetector detector;
	
	private ManagerTab mTab = null;
	private int oldPos = 0;
	
	public LocalFileFragment()
	{
		
	}
	
	public LocalFileFragment(ManagerTab mt)
	{
		mTab = mt;
	}
	
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = getActivity();
		
		View view = inflater.inflate(R.layout.fragment_localfile, null);
		fileList = (ListView)view.findViewById(R.id.localfile);
		btn_back = (ImageView)view.findViewById(R.id.btn_imgback);
		btn_local_delall = (ImageView)view.findViewById(R.id.btn_local_delall);
		tv_sydl = (TextView)view.findViewById(R.id.tv_sydl);
		
		
		
		fAdapter = new LFileAdapter(mContext,fList,this);
		fileList.setAdapter(fAdapter);
		
		tv_allsize = (TextView)view.findViewById(R.id.tv_allsize);
		
		
		getDownInfo();
		
		
//		detector = new GestureDetector(getActivity(),new OnGestureListener() {
//			
//			@Override
//			public boolean onSingleTapUp(MotionEvent e) {
//				// TODO Auto-generated method stub
//				return false;
//			}
//			
//			@Override
//			public void onShowPress(MotionEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
//					float distanceY) {
//				// TODO Auto-generated method stub
//				return false;
//			}
//			
//			@Override
//			public void onLongPress(MotionEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
//					float velocityY) {
//				// TODO Auto-generated method stub
//				
//				if (e1.getX() - e2.getX() > 120) {
//					//Logger.info("向左...");
//					((Main1Activity)mContext).showcenter();
//		            return true;
//		        } else if (e1.getX() - e2.getX() < -120) {
//		        	{//本地资源页面
//		        		FragmentTransaction t = getActivity().getSupportFragmentManager()
//								.beginTransaction();
//						t.setCustomAnimations(R.anim.push_right_in, R.anim.push_right_out);
//						LeftFragment page2 = new LeftFragment();
//						t.replace(R.id.left_frame, page2);
//						t.commit();
//						page2 = null;
//		        	}
//		            return true;
//		        }
//				
//				return false;
//			}
//			
//			@Override
//			public boolean onDown(MotionEvent e) {
//				// TODO Auto-generated method stub
//				return false;
//			}
//		});

		
//		fileList.setOnTouchListener(new OnTouchListener() {
//		
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				// TODO Auto-generated method stub
//				return detector.onTouchEvent(event);
//			}
//		});
		
		if(mTab != null)
		{
			
			fileList.setOnScrollListener(new OnScrollListener() {
				
				@Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					//Logger.info(firstVisibleItem+"xxVSoo"+oldPos);
					if(firstVisibleItem>oldPos)
					{
						mTab.hidetab();
						oldPos = firstVisibleItem;
					}else if(firstVisibleItem<oldPos){
						mTab.showtab();
						oldPos = firstVisibleItem;
					}
				}
			});
		}
		
		
		
		
		
		
		fileList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {
				// TODO Auto-generated method stub
				DownInfo di = fList.get(position);
				MovieInfo mi = new MovieInfo();
				mi.setId(di.getMovieid());
				mi.setName(di.getMoviename());
				
				Intent intent = new Intent(mContext,ViewPagerActivity.class);			
				Bundle bundle = new Bundle();
				bundle.putSerializable("movieinfo", mi);
				intent.putExtras(bundle);
				mContext.startActivity(intent);
				
				mi = null;
				
			}
		});
		
		
		
		
		btn_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FragmentTransaction t = getActivity().getSupportFragmentManager()
						.beginTransaction();
				t.setCustomAnimations(R.anim.push_right_in, R.anim.push_right_out);
				LeftFragment downfragment = new LeftFragment();
				t.replace(R.id.left_frame, downfragment);
				t.commit();
				downfragment = null;
			}
		});
		
		btn_local_delall.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub			
				showDelConfig(getActivity());
				
			}
		});
		
		
		//getLocalSize();
		
		
		return view;
	}

	public void getLocalSize()
	{
		long size = MemoryStatus.getAvailableExternalMemorySize();
		if(size==-1)
		{
			tv_sydl.setText("亲，你有SDCARD不?请检查");
		}else{
			
			tv_sydl.setText("可用空间:"+MemoryStatus.formatSize(size));
		}
	}
	
	public void showDelConfig(final Context context) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setTitle("删除确认")
            .setMessage("是否删除全部本地电影")
            .setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        
                    	for(int i=0;i<fList.size();i++)
        				{
        					DownInfo mi = fList.get(i);
        					//删除文件
        					if(FileUtils.DeleteMovieDir(mi.getMovieid()))
        					{//删除数据库记录
        						long rowid = DBHelper.getInstance(mContext).delDownInfo(mi.getMovieid());						
        					}				
        				}
                    	getDownInfo();                  	
                    }
                }
            ).setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }
            );
        alertBuilder.create().show();
    }
	
	
	
	public void onActivityCreated(Bundle savedInstanceState) {	
		super.onActivityCreated(savedInstanceState);
	}

	public void getDownInfo()
	{
		//获取数据库下载队列
		allfilesize = 0;
		
		Cursor cursor = DBHelper.getInstance(mContext).querySql("select * from downinfo where downTag = 1 order by id asc", null);
		if(null!=cursor&&cursor.getCount()>0)
		{
			Logger.error("本地文件:"+cursor.getCount());
			fList.clear();
			if(cursor.moveToFirst())
			{
				do{
					DownInfo di = new DownInfo();
					//电影名
					di.setMoviename(cursor.getString(4));
					//数据库ID
					di.setId(cursor.getInt(0));
					//电影ID
					di.setMovieid(String.valueOf(cursor.getInt(1)));
					//图片多少张
					di.setSize(cursor.getInt(2));
					//文件大小
					di.setFilesize(cursor.getLong(6));
					allfilesize += cursor.getLong(6);
					fList.add(di);
					//dMap.put(di.getMovieid(), di);
					
					di = null;
					
				}while(cursor.moveToNext());
			}							
			fAdapter.notifyDataSetChanged();
		}else{
			fList.clear();
			fAdapter.notifyDataSetChanged();
			Logger.error("下载队列为空");
		}				
		if(null!=cursor)
		{
			cursor.close();
		}			
		tv_allsize.setText(FileUtils.FormetFileSize(allfilesize));	
		getLocalSize();
	}
	
	

	@Override
	public void onResume() {
		// TODO Auto-generated method stub	
		getDownInfo();
		super.onResume();
	}
}

